package com.autumn.platform.core.logger.impl;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;

import com.autumn.platform.core.Utils;
import com.autumn.platform.core.logger.LogLevelUpdater;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;

public class LogbackLevelUpdater implements LogLevelUpdater {

    @Override
    public void update(String prefix, Level level) {
        boolean noPrefix = Utils.isBlank(prefix);
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        List<Logger> loggerList = loggerContext.getLoggerList();

        ch.qos.logback.classic.Level newLevel = convertLevel(level);
        for (Logger logger : loggerList) {
            if (noPrefix || logger.getName().startsWith(prefix)) {
                logger.setLevel(newLevel);
            }
        }
    }

    @Override
    public void set(String name, Level level) {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        loggerContext.getLogger(name).setLevel(convertLevel(level));
    }

    @Override
    public Set<String> getLogNames() {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        List<Logger> loggerList = loggerContext.getLoggerList();
        Set<String> names = new LinkedHashSet<>();
        for (Logger logger : loggerList) {
            names.add(logger.getName());
        }
        return names;
    }

    @Override
    public void setRootLevel(Level level) {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger logger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
        logger.setLevel(this.convertLevel(level));
    }

    /**
     * @param level
     * @return
     */
    private ch.qos.logback.classic.Level convertLevel(Level level) {
        ch.qos.logback.classic.Level newLevel = ch.qos.logback.classic.Level.toLevel(level.toString());
        return newLevel;
    }
}
